
/********* 返回代码变量 start****************/
var code_map=index_getMap();
//通用
code_map.put('0000',"系统成功");
code_map.put('0001',"系统错误");
code_map.put('9999',"系统错误，请尝试刷新一下或联系平台");

var code10000="10000";
//全部变量url地址
var opencaiURL='http://f.apiplus.cn/';

/********* 返回代码变量 end****************/

$(function(){

	//----判断浏览器版本-----------------
	var DEFAULT_VERSION = "8.0";
	var ua = navigator.userAgent.toLowerCase();
	var isIE = ua.indexOf("msie")>-1;
	var safariVersion;
	if(isIE){
	    safariVersion =  ua.match(/msie ([\d.]+)/)[1];
	}
	if(parseInt(safariVersion) <= parseInt(DEFAULT_VERSION) ){
		 document.getElementsByTagName('body')[0].innerHTML="<div style='width: 100%;text-align: center;font-size: 18px;margin-top:150px;'><img border='0' src='/image/browsers.jpg'></div>";
	}
	//---------------------------------------
	

});

//通用ajax方法
function doInvoke(param, callback){
	var url = "";
   if(param.url && null != param.url && "" != param.url){
	   url = param.url;
   }
   delete param.url;
 
   $.ajax({
       url: opencaiURL+url,
       dataType: 'jsonp',
       type: 'POST',
		timeout: 5000,  //设定超时5秒
       cache: false,   //禁用缓存
       jsonp: 'callback',
       success: function(result){
    	   callback(result);
		  //注：在JS采集到数据后，建议构造data:{exp:'期号',res:'结果',now:'时间'}。
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {  
          alert("加载彩票数据出错!请过10秒后重试");
       }
   });
   
}


//通用ajax方法
function doOpenInvoke(param, callback){
	var url = "";
   var ajaxType = param && param.ajaxType ? param.ajaxType : 'post';
   if(param.url && null != param.url && "" != param.url){
	   url = param.url;
   }
   delete param.url;
   delete param.ajaxType ;

   var postData = null;
   if(JSON.stringify(param) != '{}'){
	   if(param.isObject){
		   postData=param;
		   delete param.isObject;
	   }else{
		   postData =JSON.stringify(param);
	   }
   }
   
   
   $.ajax({
       url: opencaiURL+url+"-20.json",
       dataType: 'jsonp',
       type: 'POST',
		timeout: 5000,  //设定超时5秒
       cache: false,   //禁用缓存
       jsonp: 'callback',
       success: function(result){
    	   callback(result.data);
		  //注：在JS采集到数据后，建议构造data:{exp:'期号',res:'结果',now:'时间'}。
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {  
           alert("加载彩票数据出错!请过10秒后重试");
       }
   });
   
}


//判断json对象是否为空
function isEmptyObject(obj){
    for(var n in obj){return false}
    return true;
}

// html中获取 页面传过来的 参数
function GetQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
	var r = window.location.search.substr(1).match(reg);
	if (r!=null) return (r[2]); return null;
	}
	var sname = GetQueryString("name");
	if(sname!=null)
	{
	var sname_ = decodeURIComponent(sname);
	//alert(sname_);
}

//获取随机数
function GetRandomNum(Min,Max)
{
    var Range = Max - Min;
    var Rand = Math.random();
    return(Min + Math.round(Rand * Range));
}


/***********  提示框 start   **********************************/
  //成功提示框
    function succFunAlert(content,functionName){
    	swal({
            title: content,
            //text: content,
            type: "success",
            confirmButtonColor: "#48a0ff",
            confirmButtonText: "确认"
        },functionName);
    }

  //成功提示框
    function succAlert(content){
    	swal({
        	title: content,
            //text: content,
            type: "success"
        });
    }

    //错误提示框
    function errorAlert(content){
    	swal({
        	title: content,
            //text: content,
            type: "error"
        });
    }

    //警告 信息提示
    function warnAlert(content){
    	swal({
        	title: content,
            //text: content,
            type: "warning"
        });
    }

    //错误提示框,执行方法
    function errFunAlert(content,functionName){
    	swal({
            title: content,
            //text: content,
            type: "error",
            confirmButtonColor: "#48a0ff",
            confirmButtonText: "知道"
        },functionName);
    }

    //报名失败，需前往相应页面
    function errFunAlert2(butName,content,functionName){
    	swal({
            title: content,
            //text: content,
            type: "error",
            confirmButtonColor: "#48a0ff",
            confirmButtonText: butName
        },functionName);
    }

  //弹出确认框  取消关闭  / 确认执行
    function confirmAlerts(content,functionName){
    	swal({
            title: content,
            //text: content,
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#48a0ff",
            cancelButtonText: "关闭",
            confirmButtonText: "确认",
            closeOnConfirm: true
        },functionName);
    }

    function confirmAlerts2(content,functionName){
    	swal({
            title: content,
            //text: content,
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#48a0ff",
            cancelButtonText: "关闭",
            confirmButtonText: "确认",
            closeOnConfirm: false
        },functionName);
    }


    /**右上角提示框 start**/

  //信息提示框
  function loboxInfoAlert(content){
  	 Lobibox.notify('info', {
           position: 'top right',
           msg: content
       });
  }
  //警告提示框
  function loboxWarningAlert(content){
  	 Lobibox.notify('warning', {
           position: 'top right',
           msg: content
       });
  }
  //错误提示框
  function loboxErrorAlert(content){
  	 Lobibox.notify('error', {
           position: 'top right',
           msg: content
       });
  }
  //成功提示框
  function loboxSucAlert(content){
  	 Lobibox.notify('success', {
           position: 'top right',
           msg: content
       });
  }
  /**右上角提示框 end**/

/***********  提示框 end   **********************************/

//金额格式化
 function formatAmount(s) {
     if (/[^0-9\.]/.test(s)) return "invalid value";
     s = s.replace(/^(\d*)$/, "$1.");
     s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
     s = s.replace(".", ",");
     var re = /(\d)(\d{3},)/;
     while (re.test(s))
         s = s.replace(re, "$1,$2");
     s = s.replace(/,(\d\d)$/, ".$1");
     return s.replace(/^\./, "0.").toString();
 }


  //和window.open 相同！ 此方法防止浏览器拦截
  function newWin(url, id) {
	  var newTab=window.open('about:blank');
	  $.ajax({
		   success:function(data){
		    if(data){
		     newTab.location.href=url;
		    }
		   }
	  })
  }


  /**
   * 构建简单的Map集合
   */
  function index_getMap(){
	    var map_=new Object();
	    //属性加个特殊字符，以区别方法名，统一加下划线_
	    map_.put=function(key,value){    map_[key]=value;}
	    map_.get=function(key){    return map_[key];}
	    map_.remove=function(key){    delete map_[key];}
	    map_.keyset=function(){
	        var ret="";
	        for(var p in map_){
	            if(typeof p =='string' && p.substring(p.length-1)=="_"){
	                ret+=",";
	                ret+=p;
	            }
	        }
	        if(ret==""){
	            return ret.split(","); //empty array
	        }else{
	            return ret.substring(1).split(",");
	        }
	    }
	    return map_;
	}

  /**
   * 获取总页数
   * @param length  每页显示数量
   * @param totalRecord  总数量
   */
  function getTotalPages(length,totalRecord){
  	//总页数
  	var totalPages = 0;

  	totalPages = Math.floor(totalRecord % length) == 0 ? Math.floor(totalRecord / length) : Math.floor(totalRecord / length) + 1 ;

  	return totalPages;
  }

 /**
  * 获取当前时间
  * @returns {String}
  */
 function getNowFormatDate() {
	    var date = new Date();
	    var seperator1 = "-";
	    var seperator2 = ":";
	    var month = date.getMonth() + 1;
	    var strDate = date.getDate();
	    if (month >= 1 && month <= 9) {
	        month = "0" + month;
	    }
	    if (strDate >= 0 && strDate <= 9) {
	        strDate = "0" + strDate;
	    }
	    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
	            + "-" + date.getHours() + seperator2 + date.getMinutes()
	            + seperator2 + date.getSeconds();
	    return currentdate;
}

//过滤特殊字符
function stripscript(s) {
    var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\]<>/?~！@#￥……&*（）&;—|{}【】‘；：”“'。，、？]")
        var rs = "";
    for (var i = 0; i < s.length; i++) {
        rs = rs + s.substr(i, 1).replace(pattern, '');
    }
    return rs.replace(/\s+/g, "");  //最后结果去空格
}
function formatDate(time){
	if(time){
		return time.substring(0,4)+"年"+time.substring(5,7)+"月"+time.substring(8,10)+"日";
	}else{
		return '';
	}
}
//当前时间加几天
function addDateOfCurrentTime(days){
	if (days == undefined || days == '') {
        days = 1;
    }
    var date = new Date();
    date.setDate(date.getDate() + days);
    var month = date.getMonth() + 1;
    var day = date.getDate();
    return date.getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day) +" 00:00:00";
}
// 日期月份/天的显示，如果是1位数，则在前面加上'0'
function getFormatDate(arg) {
    if (arg == undefined || arg == '') {
        return '';
    }

    var re = arg + '';
    if (re.length < 2) {
        re = '0' + re;
    }

    return re;
}
/**处理null值*/
function isNull(obj){
	if(!isNaN(obj) && parseInt(obj) == 0 ){
		return false;
	}else if( obj == undefined || obj == null || obj == 'null' || obj == '' || obj == 'NaN' ){
		return true;
	}else{
		return false;
	}
};
//截取字段
function subContent(content,length,type){
	if(content && content.length>length && type==1){
		return content.substring(0,4)+' ··· '+content.substring(content.length-4,content.length);
	}if(content && content.length>length){
		return content.substring(0,length)+'···';
	}else{
		return content;
	}
}
//格式化phone
function formatPhone(phone){
	if(phone.length>10){
		return phone.substring(0,3)+"-"+phone.substring(3,7)+"-"+phone.substring(7,phone.length);
	}else{
		return phone;
	}
}

//验证码发送倒计时
var timeoutHandler;
function countDown(init, btn) {
	if (init == 0) {
		btn.html("重新发送").removeAttr("disabled");
		clearTimeout(timeoutHandler);
		return;
	} else {
		btn.attr("disabled", "disabled");
		btn.html("("+init + "秒后) 重新发送");
	}
	timeoutHandler = setTimeout(function() {countDown(init-1, btn)},1000);
};

//通过文件名，返回文件的后缀名
function fileType(name){
	var nameArr = name.split(".");
	return nameArr[nameArr.length-1].toLowerCase();
};

//校验手机号
 function checkPhone(obj){
	var phone = $(obj).val();
	if(phone == null || phone == ''){
   		return false;
	}else if(!(/^1[3|5|7|8]\d{9,9}$/.test(phone)) && phone.length  == 11|| phone.length  != 11 || !(/^[0-9]*[1-9][0-9]*$/.test(phone))){
		if(!(/^[0-9]*[1-9][0-9]*$/.test(phone))){
			$(obj).val(phone.substring(0,phone.length-1));			
		}
   		return false;
   	}
	return true;
};
//格式化金额
function formatMoney(number, decimals, dec_point, thousands_sep){
	/*
     * 参数说明：
     * number：要格式化的数字
     * decimals：保留几位小数
     * dec_point：小数点符号
     * thousands_sep：千分位符号
     * */
     number = (number + '').replace(/[^0-9+-Ee.]/g, '');
     var n = !isFinite(+number) ? 0 : +number,
    decimals = (typeof decimals === 'undefined')?2:decimals;
         prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
         sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
         dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
         s = '',
         toFixedFix = function (n, prec) {
             var k = Math.pow(10, prec);
             return '' + Math.floor(n * k) / k;
         };
     s = (prec ? toFixedFix(n, prec) : '' + Math.floor(n)).split('.');
     var re = /(-?\d+)(\d{3})/;
     while (re.test(s[0])) {
         s[0] = s[0].replace(re, "$1" + sep + "$2");
     }

     if ((s[1] || '').length < prec) {
         s[1] = s[1] || '';
         s[1] += new Array(prec - s[1].length + 1).join('0');
     }
     return "￥"+s.join(dec);
}



//退出登录
function logout(){
	$(".menu2 ul").hide();
	$(".menu2 .lgbox").show();
	//清楚token
	delMyCookie("accessToken");
	location.replace("#/login");
}

//检查登录状态
function checkLogin(){
	//刷新页面时，判断登录状态显示
	var token = getMyCookie("accessToken");
	if(token != null && token != undefined && token !=""){
		getProfile(); //成功状态下查询数据
	    $(".menu2 .lgbox").hide();
        $(".menu2 ul").show();
	}else{
		$(".menu2 ul").hide();
		$(".menu2 .lgbox").show();
	}
}


//查询个人资料
function getProfile(){
	
	var param = {
		  url:'shop/profile',
		  ajaxType:'GET'
	}
	doInvoke(param,function(data){
		if(data.code == code10000){
			//用户名不等于空时
			if(data.data.realName!=null){  
		        $("#userName").html(data.data.realName);
			}
			//用户头像
			if(data.data.photo !=null){  
				$("#userphoto").attr("src",data.data.photo);
			}
		}
	});
}




